#!/usr/bin/python
#-*- coding:utf-8 -*-
#file_op.py
#version 0.1  edited by lingyue.wkl 2011-10-1 11:52:11

#this script is userd to operate the file



import os

def get_lines(file_path):
  '''get the lines of a file.return a list'''
  f = open(file_path,"r")
  lines = f.readlines()
  f.close()
  return lines

def get_all_text(file_path):
  '''get all the text of a file .return a string'''
  f = open(file_path)
  try:
    all_text = f.read()
  finally:
    f.close()
  return all_text  

def get_all_binary_data(file_path):
  '''read binary file.return the data of the file'''
  f = open(file_path,"rb")
  try:
    all_data = f.read()
  finally:
    f.close()
  return all_data  

def read_binary(file_path,position,size):
  f = open(file_path,"rb")
  f.seek(position)
  content = f.read(size)
  f.close()
  return content

def read_binary_record(file_path,head_size,record_size,record_number):
  f = open(file_path,"rb")
  f.seek(head_size+record_size*record_number)
  content = f.read(record_size)
  f.close()
  return content

def write_lines(file_path,lines):
  '''write lines in a seq to the file'''
  f = open(file_path,"w")
  f.writelines(lines)
  f.flush()
  f.close()
  return

def write_all_text(file_path,all_text):
  '''write text to the file'''
  f = open(file_path,"w")
  f.write(all_text)
  f.close()
  return

def write_all_data(file_path,all_data):
  '''write binary data to file'''
  f = open(file_path,"wb")
  f.write(all_data)
  f.close()
  return


def append_lines(file_path,lines):
  '''append lines to a file'''
  f = open(file_path,"a")
  f.writelines(lines)
  f.flush()
  f.close()
  return
  
def is_exist(file_path):
  return os.path.exists(file_path)

def is_file(file_path):
  return os.path.isfile(file_path)

def is_dir(file_path):
  return os.path.isdir(file_path)

def replace(input_file,output_file,stext,rtext):
  '''replace string stext to rtext'''
  in_f = open(input_file)
  out_f = open(output_file,"w")
  out_f.write(in_f.read(),replace(stext,rtext))
  in_f.close()
  out_f.close()
  return True

def get_one_line(file_path,desired_line_no):
  '''get the line content from file'''
  if disired_line_no < 1:
    return ''
  for current_line_no,line in enumerate(open(file_path,'rU')):
    if current_line_no == desired_line_no - 1:
      return line
  return ''

def get_lines_count(file_path):
  '''get the total count of lines'''
  count = -1
  for count,line in  enumerate(open(file_path,'rU')):
    pass
    count += 1
  return count

